<template>
  <a-modal
    :confirmLoading="confirmLoading"
    :maskClosable="false"
    :title="model.businessFlag"
    :visible="visible"
    :width="1000"
    cancelText="关闭"
    @cancel="handleCancel"
    @ok="handleOk">
    <template slot="footer">
      <a-button @click="handleCancel">取消</a-button>
      <a-button v-if="title=='审批'" :loading="confirmLoading" type="primary" @click="handleOk(4)">
        驳回
      </a-button>
      <a-button v-if="title=='审批'" :loading="confirmLoading" type="primary" @click="handleOk(3)">
        通过
      </a-button>
    </template>
    <a-spin :spinning="confirmLoading">
      <a-divider orientation="left" style="font-weight: 600;margin-top: 0px;">基本信息</a-divider>
      <a-form :form="form">
        <a-row :gutter="24">
          <a-col :md="12" :sm="24">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="门店编码"
            >
              <a-input v-decorator="['terminalCode', validatorRules.terminalName]" :disabled="disableSubmit"
                       placeholder="请输入门店名称"/>
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="门店名称"
            >
              <a-input v-decorator="['terminalName', validatorRules.terminalName]" :disabled="disableSubmit"
                       placeholder="请输入门店名称"/>
            </a-form-item>
          </a-col>
          <!--          行政区域-->
          <a-col :md="12" :sm="24">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="行政区域"
            >
              <j-area-linkage v-model="areaLinkage" :area.sync="form.area" :city.sync="form.city"
                              :disabled="disableSubmit"
                              :province.sync="form.province" type="cascader" @change="handlePca"/>
            </a-form-item>
          </a-col>
          <!--          详细地址-->
          <a-col :md="12" :sm="24">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="详细地址"
            >
              <a-input v-decorator="['address', validatorRules.address]" :disabled="disableSubmit"
                       placeholder="请输入地址"/>
            </a-form-item>
          </a-col>
          <!--门店等级-->
          <a-col :md="12" :sm="24">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="当前门店等级"
            >
              <cn-dict-select-tag v-decorator="['terminalLevel',validatorRules.terminalLevel]" :disabled="disableSubmit"
                                  :options="{value:'dictDataCode',label:'dictDataDesc'}" :triggerChange="true"
                                  dictCode="terminal_level" placeholder="请选择门店级别"/>
            </a-form-item>
          </a-col>
          <!--门店等级-->
          <a-col :md="12" :sm="24">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="提升门店等级"
            >
              <cn-dict-select-tag v-decorator="['liftTerminalLevel',validatorRules.terminalLevel]"
                                  :disabled="disableSubmit"
                                  :options="{value:'dictDataCode',label:'dictDataDesc'}" :triggerChange="true"
                                  dictCode="terminal_level" placeholder="请选择门店级别"/>
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              label="销售额"
            >
              <a-input v-decorator="['terminalCountMoney']" :disabled="disableSubmit" placeholder=""/>
            </a-form-item>
          </a-col>
          <a-col :md="12" :sm="24">
            <a-form-item
              :labelCol="labelCol"
              :wrapperCol="wrapperCol"
              :label="model.liftTerminalLevel+'级标准'"
            >
              <a-textarea v-model="model.terminalLevelNorm" :disabled="disableSubmit" allow-clear placeholder=""
                          />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
    </a-spin>
    <!--      下方表单-->
    <a-divider orientation="left" style="font-weight: 600;margin-top: 0px;">条件达成</a-divider>
    <div style="width: 80%;margin: 24px auto">
      <a-steps :current="stepsIndex" status="error" size="small">
        <a-step v-for="(item,index) in steps" :key="index" :title="item.text"/>
      </a-steps>
    </div>
    <template v-if="model.liftTerminalLevel=='S'">
    <a-divider orientation="left" style="font-weight: 600;margin-top: 0px;">门店照片</a-divider>
      <viewer :images="[model.terminalUrl]">
        <img :src="model.terminalUrl"  shape="square" style="width: 100px;height: 100px;margin-left: 48px;margin-bottom: 12px;"/>
      </viewer>
    </template>
    <a-divider orientation="left" style="font-weight: 600;margin-top: 0px;">审核流程</a-divider>
    <div style="width: 80%;margin: 24px auto">
      <!--      status="error"-->
      <a-steps :current="stepsIndex" size="small">
        <a-step v-for="(item,index) in approval" :key="index"
                :title="item.currentNodeDesc"
                :status="item.status"
                :subTitle="item.approvalTime"
        >
          <div slot="description">
            {{item.approvalRealName }}
          </div>
          <div slot="description" v-if="item.remarks">
            意见:{{ item.remarks }}
          </div>
        </a-step>
      </a-steps>
    </div>
    <a-divider orientation="left" style="font-weight: 600;margin-top: 0px;">审批意见</a-divider>
    <a-form-item
    >
      <a-textarea v-model="remarks" :disabled="title!='审批'" allow-clear placeholder="请输入审批意见"
                  style="width:90%;margin-left:5%;min-height: 80px"/>
    </a-form-item>
  </a-modal>
</template>

<script>
import ProduceList from '../modulesForndz/ProduceList'
import newCustperson from '../modulesForndz/newCustperson'
import CodeConfigModal from '../modulesForndz/CodeConfigMdal'
import { getAction, httpAction, postAction } from '@/api/manage'
import { pick } from 'lodash'
import moment from 'moment'
import JTreeSelect from '@/components/cn-form/JTreeSelect'
import JAreaLinkage from '@comp/cn-form/CnAreaLinkage'
import { isMobile, isPermit } from '@/utils/validate'
import UploadImage from '@/components/upload-image/UploadImage'
import JImageUpload from '@/components/cn-form/JImageUpload'
import Area from '@/components/utils/Area'
import proChose from '@comp/cn-components/ProChose'
import JUpload from '@/components/cn-form/JUpload'
import TemplateModal from '@views/dms/rebatePolicy/modules/templateAdd'

export default {
  name: 'terminal-modal',
  components: {
    TemplateModal,
    JTreeSelect,
    JAreaLinkage,
    UploadImage,
    JImageUpload,
    CodeConfigModal,
    newCustperson,
    ProduceList,
    proChose,
    JUpload
  },
  data() {
    return {
      approval:[],
      disPlayImgList: [], //陈列图片
      objs: [],
      title: '',
      isDisable: false, //提交按钮状态
      sendPro: false,
      ProductAdress: [],
      remarks: '',
      dataSurces2: [],
      formChoice: [],
      showCode: false,
      remembertext: '',
      dataSource: [],
      maninumd: [],
      arrcont: [],
      cycle: 1,
      forms: [{
        isMainStr: '请选择',
        contacts: '',
        telephone: '',
        isMain: ''
      }],
      dataSurces: [],
      // dataSurces3: [],
      manobjList: [0],
      selectedRowKeys6: [],
      selectionRows6: [],
      areaData: '',
      areaLinkage: '',
      visible: false,
      visible1: false,
      model: {},
      labelCol: {
        xs: { span: 24 },
        sm: { span: 7 }
      },
      wrapperCol: {
        xs: { span: 24 },
        sm: { span: 16 }
      },
      confirmLoading: false,
      form: this.$form.createForm(this),
      //formModel表单验证规则
      rules: {
        contacts: [
          { required: true, message: '', trigger: 'submit' }
        ],
        telephone: [
          { required: true, message: '', trigger: 'submit' }
        ],
        isMainStr: [
          { required: true, message: '', trigger: 'submit' }
        ]
      },
      validatorRules: {
        //烟草许可证号
        smokeLicenceNum: {
          rules: [
            { required: true, message: '', trigger: 'submit' }
          ]
        },
        //烟草许可证有效日期
        smokeLicenceDate: {
          rules: [
            { required: true, message: '' }
          ]
        },
        //零售许可证
        retailLicenceImg: {
          rules: [
            { required: true, message: '', trigger: 'submit' }
          ]
        },
        //陈列照
        disPlayImgList: {
          rules: [
            { required: true, message: [], trigger: 'submit' }
          ]
        },
        businessLicense: {
          rules: [
            { required: true, message: '请输入营业执照号', trigger: 'submit' }
          ]
        },
        terminalName: {
          rules: [
            { required: true, message: '请输入门店名称' }
          ]
        },
        warehouseName: {
          rules: [
            { required: true, message: '请选择所属仓库' }
          ]
        },
        address: {
          rules: [
            { required: true, message: '请输入详细地址' }
          ]
        },
        dictDataCode: {
          rules: [
            { required: true, message: '请选择渠道类型' }
          ]
        },
        terminalType: {
          rules: [
            { required: true, message: '请选择门店类型' }
          ]
        },
        terminalLevel: {
          rules: [
            { required: true, message: '请选择门店等级' }
          ]
        },
        store: {
          rules: [
            { required: true, message: '请选择是否总仓' }
          ]
        },
        contacts: {
          rules: [
            { required: true, message: '' }
          ]
        },
        parentRealName: {
          rules: [
            { required: true, message: '' }
          ]
        },
        orgCode: {
          rules: [
            { required: true, message: '请选择所属组织' }
          ]
        }
      },
      steps: [],
      stepsIndex: -1,
      addOrUpdateUrl: window._CONFIG['domianURL'] + '/approval/cnTerminalApproval/saveOrUpdate',

      list: window._CONFIG['domianURL'] + '/cnTerminalController/custFindTerminalList',

      getCustmen: window._CONFIG['domianURL'] + '/terminal/cnRTermPtPos/findCustCodeForUserPos',

      warehouse: window._CONFIG['domianURL'] + '/warehouse/cnWarehouse/findPageList',

      editTerminal: window._CONFIG['domianURL'] + '/terminal/cnRTermPtPos/findProductsByCustCode'
    }
  },
  created() {
    this.initAreaData()
    // console.log(this.areaData);
  },
  methods: {
    add() {
      // this.edit({})
      this.form.resetFields()
      this.visible = true
    },
    updataInfo(params) {
      let traget = [{
          text: '非我道具',
          show: params.whetherProduct
        },
        {
          text: 'A类陈列位置',
          show: params.isClassDisplay
        },
        {
          text: '陈列数量占比50%',
          show: params.displayWhether
        },
        {
          text: '销售额800',
          show: params.saleWhether
        },
        {
          text: '可提升等级',
          show: true
        },
      ]
      let index = 0
      if (params.whetherProduct) {
        index = 0
      }
      if (params.liftTerminalLevel == 'C') {
        traget[0].text = '非我产品'
        traget[3].text = '销售额1000'
      }
      if (params.liftTerminalLevel == 'B') {
        traget[3].text = '销售额3000'
      }
      if (params.liftTerminalLevel == 'A') {
        traget[3].text = '销售额7000'
        traget.splice(2, 1)
      }
      if (params.liftTerminalLevel == 'S') {
        traget[3].text = '销售额12000'
        traget.splice(1, 1)
      }
      if (['C', 'B'].includes(params.liftTerminalLevel)) {
        traget.splice(1, 2)
      }
      index = traget.findIndex(item => item.show != true)
      if (index == -1) {
        index = traget.length+1
      }

      this.$set(this, 'steps', traget)
      this.$set(this, 'stepsIndex', index)
    },
    edit(record) {
      if (record.extendVos) {
        this.forms = record.extendVos
      } else {
        //新增时，防止联系人数据回显
        this.forms = [{
          isMainStr: '请选择',
          contacts: '',
          telephone: '',
          isMain: ''
        }]
      }
      this.ProductAdress = []
      this.form.resetFields()
      this.model = Object.assign({}, record)
      let pca = this.model.province + '/' + this.model.city + '/' + this.model.area
      this.areaLinkage = this.areaData.getAreaCodeByText(pca) || ''
      this.visible = true
      this.getApproval()
      this.updataInfo(record)
      this.$nextTick(() => {
        setTimeout(() => {
          this.form.setFieldsValue({
            orgName: '请选择'
          })
          this.form.setFieldsValue(pick(this.model, Object.keys(this.model)))
        }, 200)
      })

    },
    async getApproval() {
      if (this.model.id) {
        let res = await postAction('/approval/cnApprovalLog/findNodeLogList', {
          businessFlag: this.model.businessFlag,
          businessId: this.model.id
        })
        if (res.success) {
          this.approval = res.result.map((item,index) => {
            if (item.approvalStatus == 4) {
              item.status = 'error'
            } else if (item.approvalTime) {
              item.status = 'finish'
            }else if ( !item.approvalTime&& res.result[index-1].approvalTime) {
              item.status = 'process'
            }else {
              item.status = 'wait'
            }
            return item
          })
        } else {
          this.$message.error(res.message)
        }
      }
    },
    close() {
      this.$emit('close')
      this.visible = false
      this.disPlayImgList = []
      this.approval=[]
      this.remarks = ''
    },
    handleOk(status) {
      let formData = {
        approvalStatus: status,
        remarks: this.remarks,
        id: this.model.id,
        terminalCode: this.model.terminalCode
      }
      this.confirmLoading = true
      let that = this
      httpAction(this.addOrUpdateUrl, formData, 'post').then((res) => {
        if (res.success) {
          that.$message.success(res.message)
          that.$emit('ok')
          that.close()
        } else {
          that.$message.warning(res.message)
        }
      }).finally(() => {
        that.confirmLoading = false
      })
    },
    handleCancel() {
      this.close()
    },
    initAreaData() {
      if (!this.areaData) {
        this.areaData = new Area()
      }
    },
  }
}
</script>

<style scoped>
.gonghuoxinxi {
  width: 100%;
  border-bottom: 1px dashed black;
  margin: 10px 0;
  padding: 15px 5px;
  display: flex;
  flex-direction: column;
}
</style>
